package com.xxx.client.android.db;

import java.util.ArrayList;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.xxx.client.android.CustomApplication;

/**
 * Database implementation using Android SQLite
 */
public class DatabaseImpl implements Database {

	private static final String DB_NAME = CustomApplication.TAG + "_history.db";
	private static final String TABLE_HISTORYLIST = "history";

	private Activity mActivity;

	public DatabaseImpl(Activity activity) {
		this.mActivity = activity;
		create();
	}

	/**
	 * Initializes database and tables
	 */
	private void create() {
		SQLiteDatabase db = mActivity.openOrCreateDatabase(DB_NAME,
				Context.MODE_PRIVATE, null);

		// create tables if necessary

		db.execSQL("CREATE TABLE IF NOT EXISTS "
				+ TABLE_HISTORYLIST
				+ " (history_id integer primary key autoincrement, history_name VARCHAR, history_url VARCHAR, history_type VARCHAR);");

		db.close();
	}

	@Override
	public void deleteHistory(int[] historyIds) {
		SQLiteDatabase db = mActivity.openOrCreateDatabase(DB_NAME,
				Context.MODE_PRIVATE, null);

		for (int i : historyIds) {
			db.delete(TABLE_HISTORYLIST, "history_id = ?",
					new String[] { String.valueOf(i) });
		}

		db.close();
	}

	@Override
	public ArrayList<History> getHistoryList() {
		ArrayList<History> historyList = null;
		SQLiteDatabase db = mActivity.openOrCreateDatabase(DB_NAME,
				Context.MODE_PRIVATE, null);

		String[] columns = { "history_id", "history_name", "history_url",
				"history_type" };
		Cursor query = db.query(TABLE_HISTORYLIST, columns, null, null, null,
				null, "history_id DESC");

		if (query != null) {
			historyList = query.moveToFirst() ? new ArrayList<History>() : null;
			while (!query.isAfterLast()) {
				historyList.add(new HistoryDatabaseBuilder().build(query));
				query.moveToNext();
			}
		}

		query.close();

		db.close();
		return historyList;
	}

	@Override
	public void addHistory(History history) {
		SQLiteDatabase db = getDb();

		// put history data into the table
		ContentValues values = new HistoryDatabaseBuilder()
				.deconstruct(history);

		String[] whereArgs = { "" + history.getHistoryId() };
		int row_count = db.update(TABLE_HISTORYLIST, values, "history_id=?",
				whereArgs);

		if (row_count == 0) {
			db.insert(TABLE_HISTORYLIST, null, values);
		}

		db.close();
	}

	private SQLiteDatabase getDb() {
		return mActivity.openOrCreateDatabase(DB_NAME, Context.MODE_PRIVATE,
				null);
	}

}
